<template>
  <div class="login">
    <t-form
      ref="form"
      :class="['item-container', `login-${type}`]"
      :data="formData"
      :rules="FORM_RULES"
      label-width="0"
      @submit="onSubmit"
    >
      <t-tabs v-model="value" class="tab">
        <t-tab-panel :value="1" label="账号密码登录">
          <!-- 账号密码登录 -->
          <div v-if="type == 'password'" class="form">
            <t-form-item name="account">
              <t-input
                v-model="formData.account"
                size="large"
                :maxlength="50"
                @blur="testPhoneEmail"
                placeholder="请输入邮箱/手机号"
                clearable
              >
                <template #prefix-icon>
                  <user-icon />
                </template>
              </t-input>
            </t-form-item>

            <t-form-item name="password">
              <t-input
                v-model="formData.password"
                size="large"
                :type="showPsw ? 'text' : 'password'"
                clearable
                key="password"
                placeholder="请输入登录密码"
              >
                <template #prefix-icon>
                  <lock-on-icon />
                </template>
                <template #suffix-icon>
                  <browse-icon v-if="showPsw" @click="showPsw = !showPsw" key="browse" />
                  <browse-off-icon v-else @click="showPsw = !showPsw" key="browse-off" />
                </template>
              </t-input>
            </t-form-item>
          </div>
        </t-tab-panel>
        <t-tab-panel :value="2" label="手机快捷登录">
          <!-- 手机快捷登录 -->
          <div class="form">
            <t-form-item name="phone">
              <t-input
                v-model="formData.phone"
                size="large"
                :maxlength="11"
                @blur="testPhone"
                placeholder="请输入您的手机号"
                clearable
              >
                <template #prefix-icon>
                  <user-icon />
                </template>
              </t-input>
            </t-form-item>
            <t-form-item name="verifyCode">
              <t-input
                v-model="formData.verifyCode"
                size="large"
                placeholder="请输入验证码"
                key="verifyCode"
                class="verify-inp"
                clearable
              />
              <t-button variant="outline" :disabled="countDown > 0" @click="sendCode" class="verify-btn">
                {{ countDown == 0 ? '发送验证码' : `${countDown}秒后可重发` }}
              </t-button>
            </t-form-item>
          </div>
        </t-tab-panel>
      </t-tabs>

      <div class="check-container remember-pwd">
        <t-checkbox v-model="checked">
          <span>
            我已阅读并同意
            <a href="https://www.pis360.com/privacy-policy" target="_blank" style="margin-right: 0">隐私政策</a>
            和
            <a href="https://www.pis360.com/agreement" target="_blank">用户协议</a>
          </span>
        </t-checkbox>
      </div>
      <t-form-item v-if="type !== 'qrcode'" class="btn-container">
        <t-button block size="large" type="submit"> 登录 </t-button>
      </t-form-item>
    </t-form>
    <swiper />
  </div>
</template>
<script>
import Vue from 'vue';
import { verificationCode } from '@/service/login/index';
import Swiper from './Swiper.vue';
import { UserIcon, LockOnIcon, BrowseOffIcon, BrowseIcon } from 'tdesign-icons-vue';
import CryptoJS from 'crypto-js';
import img1 from '@/assets/login/slideshow1.png';
// import { requestAccountLogin } from '@/service/login/index';
// import { setLocalStorage } from '@/utils/storage';

const INITIAL_DATA = {
  phone: '',
  account: '',
  password: '',
  verifyCode: '',
};

const FORM_RULES = {
  phone: [{ required: true, message: '手机号必填', type: 'error' }],
  account: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
  verifyCode: [{ required: true, message: '验证码必填', type: 'error' }],
};
export default Vue.extend({
  name: 'Login',
  components: {
    UserIcon,
    LockOnIcon,
    BrowseOffIcon,
    BrowseIcon,
    Swiper,
  },
  data() {
    return {
      current: 0, // 轮播图
      checked: false,
      value: 1,
      FORM_RULES,
      type: 'password',
      formData: { ...INITIAL_DATA },
      showPsw: false,
      countDown: 0,
      intervalTimer: null,
      slideshows: [
        {
          img: img1,
        },
      ],
    };
  },
  watch: {
    value() {
      this.formData.password = '';
      this.formData.verifyCode = '';
      this.formData.phone = '';
      this.formData.account = '';
    },
  },
  beforeDestroy() {
    clearInterval(this.intervalTimer);
  },
  methods: {
    switchType(val) {
      this.type = val;
    },
    // 登录
    async onSubmit({ validateResult }) {
      if (validateResult === true) {
        if (!this.checked) {
          this.$message.warning('请同意英斯盾隐私政策和用户协议');
          return;
        }
        // 账号密码登录
        if (this.value === 1) {
          if (!this.testPhoneEmail()) return;

          const userLoginDTO = {
            loginUser: this.formData.account,
            password: CryptoJS.MD5(this.formData.password).toString(),
          };
          await this.$store.dispatch('user/loginByCount', userLoginDTO);
        } else {
          // 手机验证码登录
          if (this.testPhone()) return;
          const userLoginDTO = { code: this.formData.verifyCode, phone: this.formData.phone };
          await this.$store.dispatch('user/loginByPhone', userLoginDTO);
        }
        this.$router.replace({ path: '/dashboard' });
      }
    },
    // 发送验证码
    async sendCode() {
      const phone = { phone: this.formData.phone };
      if (this.testPhone()) {
        this.$message.error('请输入正确的手机号');
        return;
      }
      await verificationCode(phone);

      this.countDown = 60;
      this.intervalTimer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1;
        } else {
          clearInterval(this.intervalTimer);
          this.countDown = 0;
        }
      }, 1000);
    },
    // 账号密码登录时 判断手机号或者邮箱是否正确
    // 手机快捷登录时 判断手机号是否正确
    testPhoneEmail() {
      if (this.formData.account === '' || this.formData.account === '') return;
      // account
      const phoneNumber = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (phoneNumber.test(this.formData.account) || email.test(this.formData.account)) return true;
      this.$message.error('账号不正确');
      return false;
    },
    testPhone() {
      if (this.formData.account === '') return;
      const phoneNumber = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      if (!phoneNumber.test(this.formData.phone)) {
        this.$message.error('手机号不正确');
        return false;
      }
      return true;
    },
  },
});
</script>

<style lang="less" scoped>
.tab {
  .form {
    padding-top: 14px;
    margin-bottom: 20px;
    width: 100%;
    .verify-btn {
      width: 40%;
    }
  }
}
/deep/.tab .t-tabs {
  width: 35vw;
}
</style>
